"use client";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Heart, Bookmark } from "lucide-react";

export default function PostCard({ post }: { post: any }) {
  const [liked, setLiked] = useState(post.liked ?? false);
  const [bookmarked, setBookmarked] = useState(post.bookmarked ?? false);
  const [imgLoaded, setImgLoaded] = useState(false);
  const visibleAt = useRef<number | null>(null);
  const router = useRouter();

  useEffect(() => {
    const onVisible = () => {
      visibleAt.current = Date.now();
    };
    const onHidden = () => {
      const now = Date.now();
      const dwellMs = visibleAt.current ? now - (visibleAt.current as number) : 0;
      visibleAt.current = null;
      if (dwellMs > 500) {
        fetch("/api/track/view", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ postId: post.id, dwellMs, scene: "home" }) });
      }
    };

    const io = new IntersectionObserver((entries) => {
      const e = entries[0];
      if (e.isIntersecting) onVisible();
      else onHidden();
    }, { threshold: 0.5 });
    const el = document.getElementById(`post-${post.id}`);
    if (el) io.observe(el);
    return () => io.disconnect();
  }, [post.id]);


  const tags: string[] = Array.isArray(post.tags) ? post.tags : [];

  const handleCardClick = (e: React.MouseEvent) => {
    // 如果点击的是按钮，不触发跳转
    if ((e.target as HTMLElement).closest('button')) {
      return;
    }
    router.push(`/post/${post.id}`);
  };

  const handleLikeClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    const res = await fetch("/api/toggle-like", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ postId: post.id }) });
    if (res.ok) {
      const data = await res.json();
      setLiked(data.liked);
    }
  };

  const handleBookmarkClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    const res = await fetch("/api/toggle-bookmark", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ postId: post.id }) });
    if (res.ok) {
      const data = await res.json();
      setBookmarked(data.bookmarked);
    }
  };

  return (
    <div 
      id={`post-${post.id}`} 
      onClick={handleCardClick}
      className="rounded-2xl overflow-hidden bg-white card-shadow hover:card-shadow-hover transition-all duration-300 hover:scale-[1.02] cursor-pointer"
    >
      {/* 图片容器 */}
      <div className="relative w-full aspect-[3/4]">
        {/* 图片加载占位符 */}
        {!imgLoaded && (
          <div className="absolute inset-0 image-loading rounded-t-2xl" />
        )}
        
        {post.coverUrl && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            alt={post.title}
            src={post.coverUrl}
            className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-500 ${
              imgLoaded ? "opacity-100" : "opacity-0"
            }`}
            loading="lazy"
            onLoad={() => setImgLoaded(true)}
            onError={() => setImgLoaded(true)}
          />
        )}
        
        {/* 渐变遮罩和内容 */}
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />
        
        {/* 标签 */}
        {tags.length > 0 && imgLoaded && (
          <div className="absolute top-3 left-3 flex flex-wrap gap-1">
            {tags.slice(0, 2).map((t: string) => (
              <span 
                key={t} 
                className="text-xs px-2 py-1 rounded-full bg-white/90 text-gray-800 font-medium backdrop-blur-sm"
              >
                #{t}
              </span>
            ))}
          </div>
        )}
        
        {/* 标题 */}
        <div className="absolute bottom-3 left-3 right-3">
          <h3 className="text-white font-semibold text-sm leading-tight line-clamp-2 drop-shadow-lg">
            {post.title}
          </h3>
        </div>
      </div>
      
      {/* 底部交互区域 */}
      <div className="p-3">
        <div className="flex items-center justify-between">
          <button 
            onClick={handleLikeClick}
            className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-full transition-all duration-200 ${
              liked 
                ? "text-red-500 bg-red-50" 
                : "text-gray-600 bg-gray-50 hover:bg-gray-100 active:scale-95"
            } ${liked ? 'animate-heart' : ''}`}
          >
            <Heart 
              size={14} 
              fill={liked ? "currentColor" : "none"} 
              stroke="currentColor"
              className="transition-all duration-200"
            />
            <span className="font-medium">赞</span>
          </button>
          
          <button 
            onClick={handleBookmarkClick}
            className={`flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-full transition-all duration-200 ${
              bookmarked 
                ? "text-amber-600 bg-amber-50" 
                : "text-gray-600 bg-gray-50 hover:bg-gray-100 active:scale-95"
            }`}
          >
            <Bookmark 
              size={14} 
              fill={bookmarked ? "currentColor" : "none"} 
              stroke="currentColor"
              className="transition-all duration-200"
            />
            <span className="font-medium">收藏</span>
          </button>
        </div>
      </div>
    </div>
  );
}